package com.sf.dlb.service;

import com.sf.dlb.bean.BzyOauthBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.BzyOauthInfo;
import com.sf.dlb.jpa.repository.BzyOauthRepository;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.HttpClientUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class BzyOauthService {
    private static Logger logger = LoggerFactory.getLogger(BzyOauthService.class);

    @Autowired
    private BzyOauthRepository bzyOauthRepository;

    /**
     * 获取认证token
     *  从数据库获取
     * @return
     */
    public ResultVO getOauth(){
        return getOauth(false);
    }
    /**
     * 获取认证token
     * OauthFlag 是否重新获取
     * @return
     */
    public ResultVO getOauth(boolean OauthFlag){
        //1 八爪鱼API授权；
        BzyOauthInfo bzyOauthInfo=bzyOauthRepository.findByUsernameAndDelFlag("tancs12345","0");
        if(null==bzyOauthInfo){
            logger.info("getNewList bzyOauthInfo is null ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"getNewList bzyOauthInfo is null");
        }
        //如果token为null 或者 是否强制刷token
        if(StringUtils.isBlank(bzyOauthInfo.getAccessToken())|| OauthFlag){
            boolean oauthFlag=getOauth(bzyOauthInfo); //只有第一次为空
            if(!oauthFlag){
                logger.info("getNewList getOauth is "+oauthFlag);
                return ResultVOUtil.error(ResponseConstant.ERROR,"getNewList getOauth is "+oauthFlag);
            }
            bzyOauthInfo=bzyOauthRepository.findByUsernameAndDelFlag("tancs12345","0");
        }
        return ResultVOUtil.success(bzyOauthInfo);
    }
    /**
     * 获取认证token
     * @param bzyOauthInfo
     * @return
     */
    public boolean getOauth(BzyOauthInfo bzyOauthInfo){
        logger.info("getOauth 第一次为空&强制刷新  ");
        String grantUrl=bzyOauthInfo.getGrantUrl();
        Map<String,String> grantMap=new HashMap<>();
        grantMap.put("username",bzyOauthInfo.getUsername());
        grantMap.put("password",bzyOauthInfo.getPassword());
        grantMap.put("grant_type",bzyOauthInfo.getGrantType());
        HttpResponse response= HttpClientUtils.postFrom(grantUrl,grantMap);
        return handlerOauth(response,bzyOauthInfo);
    }
    /**
     * 刷新认证token
     * @param bzyOauthInfo
     * @return
     */
    public boolean refreshOauth(BzyOauthInfo bzyOauthInfo){
        logger.info("  refreshOauth  ");
        String grantUrl=bzyOauthInfo.getGrantUrl();
        Map<String,String> grantMap=new HashMap<>();
        grantMap.put("refresh_token",bzyOauthInfo.getRefreshToken());
        grantMap.put("grant_type","refresh_token");
        HttpResponse response=HttpClientUtils.postFrom(grantUrl,grantMap);
        return handlerOauth(response,bzyOauthInfo);
    }

    /**
     * 处理认证请求
     * @param response
     * @param bzyOauthInfo
     * @return
     */
    public boolean handlerOauth(HttpResponse response,BzyOauthInfo bzyOauthInfo){
        int statusCode=response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        String body = "";
        logger.info("handlerOauth statusCode is == "+statusCode);
        if(statusCode==200){
            if (entity != null) {
                try {
                    body = EntityUtils.toString(entity, "utf-8");
                    logger.info("handlerOauth body is == "+body);
                    BzyOauthBean oauthBean= (BzyOauthBean) GsonUtils.getInstance().fromJson(body, BzyOauthBean.class);
                    //更新token
                    bzyOauthInfo.setAccessToken(oauthBean.getAccess_token());
                    bzyOauthInfo.setTokenType(oauthBean.getToken_type());
                    bzyOauthInfo.setExpiresIn(oauthBean.getExpires_in());
                    bzyOauthInfo.setRefreshToken(oauthBean.getRefresh_token());
                    bzyOauthInfo.setUpdateDate(new Date());
                    bzyOauthInfo=bzyOauthRepository.save(bzyOauthInfo);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }

        return false;
    }
}
